/*
 * Copyright (c) 2023, 2024,yzc.cn All rights reserved.
 *
 */
package com.by.common.controller;

import com.by.common.ResultStatus;
import com.by.common.exception.ValidateException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Project: erp-cloud-api - BaseController</p>
 * <p>Powered by yzc On 2024-01-08 17:24:17</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */

public class BaseController {

    /**
     * 验证
     *
     * @param result
     */
    public void validator(BindingResult result){
        //读取验证失败的错误列表
        List<FieldError> fieldErrors = result.getFieldErrors();
        if (fieldErrors.size()>0){
            //说明有异常,使用map记录异常
            Map errors = new HashMap<>();
            //遍历fieldErrors集合，将异常信息存入map中
            fieldErrors.forEach(f->{
                errors.put(f.getField(),f.getDefaultMessage());
            });
            //存在异常信息，抛出异常，中止程序运行
            throw new ValidateException(errors);
        }
    }
}
